package com.milkshopbackend.milkshop.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.milkshopbackend.milkshop.Service.ScheduledTaskService;
import com.milkshopbackend.milkshop.entity.ScheduledTask;
import com.milkshopbackend.milkshop.mapper.ScheduledTaskMapper;
import org.springframework.scheduling.support.CronExpression;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class ScheduledTaskServiceImpl extends ServiceImpl<ScheduledTaskMapper, ScheduledTask> implements ScheduledTaskService {

    @Override
    @Transactional
    public void createTask(String taskName, String taskKey, String taskDesc, String cronExpression) {
        // 验证cron表达式
        if (!CronExpression.isValidExpression(cronExpression)) {
            throw new IllegalArgumentException("Invalid cron expression: " + cronExpression);
        }

        // 查找是否已存在相同的任务
        LambdaQueryWrapper<ScheduledTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ScheduledTask::getTaskKey, taskKey);
        ScheduledTask existingTask = getOne(wrapper);
        ScheduledTask task;
        
        if (existingTask != null) {
            // 更新已存在的任务
            task = existingTask;
            task.setTaskName(taskName);
            task.setTaskDesc(taskDesc);
            task.setCronExpression(cronExpression);
            task.setUpdateTime(LocalDateTime.now());
        } else {
            // 创建新任务
            task = new ScheduledTask();
            task.setTaskName(taskName);
            task.setTaskKey(taskKey);
            task.setTaskDesc(taskDesc);
            task.setCronExpression(cronExpression);
            task.setTaskStatus(0); // 待执行
            task.setCreateTime(LocalDateTime.now());
            task.setUpdateTime(LocalDateTime.now());
        }
        
        // 计算下次执行时间
        CronExpression cron = CronExpression.parse(cronExpression);
        task.setNextExecuteTime(cron.next(LocalDateTime.now()));

        saveOrUpdate(task);
    }

    @Override
    @Transactional
    public void updateTaskStatus(String taskKey, Integer taskStatus, String errorMsg) {
        ScheduledTask task = getTaskByKey(taskKey);
        if (task != null) {
            task.setTaskStatus(taskStatus);
            task.setLastExecuteTime(LocalDateTime.now());
            task.setErrorMsg(errorMsg);
            task.setUpdateTime(LocalDateTime.now());

            if (taskStatus == 2) { // 执行成功，更新下次执行时间
                CronExpression cron = CronExpression.parse(task.getCronExpression());
                task.setNextExecuteTime(cron.next(LocalDateTime.now()));
            }

            updateById(task);
        }
    }

    @Override
    @Transactional
    public void updateNextExecuteTime(String taskKey, String cronExpression) {
        if (!CronExpression.isValidExpression(cronExpression)) {
            throw new IllegalArgumentException("Invalid cron expression: " + cronExpression);
        }

        ScheduledTask task = getTaskByKey(taskKey);
        if (task != null) {
            task.setCronExpression(cronExpression);
            CronExpression cron = CronExpression.parse(cronExpression);
            task.setNextExecuteTime(cron.next(LocalDateTime.now()));
            task.setUpdateTime(LocalDateTime.now());
            updateById(task);
        }
    }

    @Override
    public ScheduledTask getTaskByKey(String taskKey) {
        LambdaQueryWrapper<ScheduledTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ScheduledTask::getTaskKey, taskKey);
        return getOne(wrapper);
    }
} 